package com.nassir.chatroom.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;

import com.nassir.chatroom.frame.MainFrame;
import com.nassir.chatroom.util.Logs;
import com.nassir.chatroom.util.Sleeper;

/**
 * 消息
 * @author nassir.wen
 * @date 2012-12-9 下午05:47:55
 * @Copyright Copyright (c) 2011
 */
public class Message extends Thread {
		Socket client;
		MainFrame mainFrame;

		public Message(SocketClient client, MainFrame mainFrame) {
			this.client = client.getClient();
			this.mainFrame = mainFrame;
		}

		public void run() {
			try {
				getMessage();
				Sleeper.sleep(1);
			} catch(SocketException se){
				Logs.error("服务器断开连接,请重新连接");
			}catch (IOException e) {
				e.printStackTrace();
			}
		}

		private void getMessage() throws IOException {
			BufferedReader br = new BufferedReader(new InputStreamReader(
			        client.getInputStream()));
			String str = null;
			while ((str = br.readLine()) != null) {
				mainFrame.getReceiveBox().append(str + "\n");
				if (str.endsWith("bye!"))
					break;
			}
			br.close();
		}
		
		public static void sendMessage(SocketClient client,String message) throws IOException {
	        BufferedWriter writeToServer = new BufferedWriter(
	                new OutputStreamWriter(client.getClient().getOutputStream()));
	        while (message != null) {
	            writeToServer.write(message + "\n");
	            writeToServer.flush();
	            if (message.endsWith("bye!")) {
	                break;
	            }
	            Logs.info("发送成功");
	            message = null;
	        }
	    }
	}